package com.koron.system.org.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.PageQuery;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.org.dto.OrgDto;
import com.koron.bean.system.org.query.OrgQuery;
import com.koron.bean.system.staff.StaffBean;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.annocation.CasUser;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.system.common.util.TypeTreeVo;
import com.koron.system.org.bean.WorkFlowDepartment;
import com.koron.system.org.service.OrgService;
import com.koron.system.schedule.UnifyOrgUserTask;
import com.koron.system.staff.service.StaffService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @ClassName OrgController
 * @description
 * @Author zhouj
 * @Date 2021/7/6 9:29
 */
@RestController
@RequestMapping("/system/org")
@Api(tags = "组织管理")
@Slf4j
public class OrgController {

    @Autowired
    OrgService orgService;

    @Autowired
    StaffService staffService;

    @Autowired
    UnifyOrgUserTask unifyOrgUserTask;

    @ApiOperation(value = "新增组织")
    @PostMapping("/insertOrg")
    public Response insertOrg(@RequestBody OrgBean orgBean, @CasUser EamUser user) {
        return Response.success(orgService.insertOrg(user, orgBean));
    }

    @ApiOperation(value = "修改组织")
    @PutMapping("/updateOrg")
    public Response updateOrg(@RequestBody OrgBean orgBean, @CasUser EamUser user) {
        return Response.success(orgService.updateOrg(user, orgBean));
    }

    @ApiOperation(value = "删除组织")
    @DeleteMapping("/delete")
    public Response deleteOrg(String id) {

        OrgQuery orgBean = new OrgQuery();
        orgBean.setParent(id);
        List<OrgBean> orgBeans = orgService.queryNextOrgList(orgBean);
        //该组织节点可能被权限，人员关联到
        if (!CollectionUtils.isEmpty(orgBeans)) {
            return Response.fail("请先删除子节点");
        }
        //节点下不能有人
        StaffBean staffBean = new StaffBean();
        staffBean.setOrgId(id);
        Long aLong = staffService.queryStaffListByOrgCount(0, staffBean);

        if (aLong >= 1) {
            return Response.fail("请先删除组织节点下用户");
        }

        return Response.success(orgService.deleteOrg(id));
    }

    @ApiOperation(value = "删除组织list")
    @DeleteMapping("/deleteList")
    public Response deleteOrg(@RequestParam("ids") List<String> ids) {
        return Response.success(orgService.deleteOrgList(ids));
    }

    @ApiOperation(value = "查询组织树")
    @GetMapping("/queryOrgTree")
    public Response<List<TypeTreeVo>> queryOrgTree(OrgQuery orgQuery) {
        String name = orgQuery.getName();

        if (StringUtils.isNotEmpty(name)) {
            orgQuery.setName(name.replace(" ", ""));
        }
        if (StringUtils.isNotBlank(orgQuery.getName()) && Pattern.matches("[a-zA-Z]*", orgQuery.getName())) {
            //如果是拼音
            String keyword = orgQuery.getName().toLowerCase();
            orgQuery.setName(null);
            orgQuery.setNamePy(keyword);
        }
        return Response.success(orgService.queryOrgTree(orgQuery));
    }

    @ApiOperation(value = "查询组织列表")
    @GetMapping("/queryOrgList")
    public Response queryOrgList(OrgQuery orgQuery, PageQuery pageQuery) {

        String name = orgQuery.getName();

        if (StringUtils.isNotEmpty(name)) {
            orgQuery.setName(name.replace(" ", ""));
        }

        if (StringUtils.isNotBlank(orgQuery.getName()) && Pattern.matches("[a-zA-Z]*", orgQuery.getName())) {
            //如果是拼音
            String keyword = orgQuery.getName().toLowerCase();
            orgQuery.setName(null);
            orgQuery.setNamePy(keyword);
        }

        PageHelper.startPage(pageQuery.getPage(), pageQuery.getPageSize());

        PageInfo<OrgBean> orgBeanPageInfo = new PageInfo<>(orgService.queryNextOrgList(orgQuery));

        return Response.success(orgBeanPageInfo.getList(), orgBeanPageInfo.getTotal());

        //return Response.success(orgService.queryNextOrgList(orgBean, queryBean), orgService.queryNextOrgListCount(orgBean));
    }

    @ApiOperation(value = "查询组织列表(不分页)")
    @GetMapping("/queryNextOrgList")
    public Response<List<OrgBean>> queryNextOrgList(OrgQuery orgQuery) {

        String name = orgQuery.getName();

        if (StringUtils.isNotEmpty(name)) {
            orgQuery.setName(name.replace(" ", ""));
        }

        if (StringUtils.isNotBlank(orgQuery.getName()) && Pattern.matches("[a-zA-Z]*", orgQuery.getName())) {
            //如果是拼音
            String keyword = orgQuery.getName().toLowerCase();
            orgQuery.setName(null);
            orgQuery.setNamePy(keyword);
        }

        return Response.success(orgService.queryNextOrgList(orgQuery));

    }

    @ApiOperation(value = "查询多个组织的部门信息")
    @GetMapping("/queryDeptByOrgIdList")
    public Response<List<OrgBean>> queryDeptByOrgIdList(OrgDto orgDto) {
        return Response.success(orgService.queryDeptByOrgIdList(orgDto));
    }

    @ApiOperation(value = "查询单个组织信息")
    @GetMapping("/querySingleOrg")
    public Response querySingleOrg(OrgBean orgBean) {
        return Response.success(orgService.querySingleOrg(orgBean));
    }

    @GetMapping("/getWorkFlowDepartmentList")
    @ApiOperation("获取工作流组织")
    public List<WorkFlowDepartment> getWorkFlowDepartmentList() {
        try {
            return orgService.getWorkFlowDepartmentList();
        } catch (Exception e) {
            log.error("查询组织树失败", e);
            return new ArrayList<>();
        }
    }

    @ApiOperation(value = "初始化拼音")
    @PutMapping("/resetPy")
    public Response resetPy(String id) {
        return Response.success(orgService.resetPy());
    }

    @ApiOperation(value = "获取组织的可用层级切换")
    @GetMapping("/getOrgLevel")
    public Response getOrgLevel(String orgId) {
        return Response.success(orgService.getOrgLevel(orgId));
    }

    @ApiOperation(value = "通过组织id获取部门")
    @GetMapping("/queryDeptByOrgId")
    public Response<OrgBean> queryDeptByOrgId(String orgId) {
        return Response.success(orgService.queryDeptByOrgId(orgId));
    }

    @GetMapping("/getSortByName")
    public Integer getSortByName(String name) {
        return orgService.getSortByName(name);
    }


    @ApiOperation(value = "获取线路跟进部门")
    @GetMapping("/queryLineFollowOrg")
    public Response<List<TypeTreeVo>> queryLineFollowOrg(OrgQuery orgQuery) {
        if ("water_02".equals(ThreadLocalContext.get().getCurrDs())) {
            orgQuery.setOrgIds(Arrays.asList("000232", "000175", "000152", "000574", "000330"));
        }
        return queryOrgTree(orgQuery);
    }

    // YJ TODO 2023/12/12 17:30 同步统一用户平台组织
    @ApiOperation(value = "手动同步统一用户平台组织")
    @GetMapping("/syncOrgAndUser")
    public Response syncOrgAndUser(){
        unifyOrgUserTask.callInUpAllOrgNode();
        return Response.ok();
    }
}
